﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using PddHelper.Api;
using PddHelper.Models;
using System.Net;
using WebApiExtend;

namespace WebApiExtend
{
    /// <summary>
    /// 异常拦截器
    /// 通过Execption Filter 过滤器可以进行全局的异常日志收集 等操作。
    /// </summary>
    public class ExecptionFilter : Base, IExceptionFilter
    {
        private ILogger<ExecptionFilter> _logger;

        /// <summary>
        /// 构造注入日志组件
        /// </summary>
        /// <param name="logger"></param>
        public ExecptionFilter(ILogger<ExecptionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            //记录日志收集
            var logEntity = base.InitLogModel(context.HttpContext);
            base.LogInfo(logEntity);
            base.LogError($"\n{logEntity.requestraw}\nMessage:{context?.Exception?.Message}\nStackTrace:{context?.Exception?.StackTrace}");


            var result = new ApiResult<object>
            {
                Code = ApiStatusCode.InternalServerError,
                Msg = "服务器内部异常",
                Data = new
                {
                    context?.Exception?.Message,
                    context?.Exception?.StackTrace
                }
            };

            context.Result = new ContentResult
            {
                StatusCode = (int)HttpStatusCode.InternalServerError,
                ContentType = "application/json;charset=utf-8",
                Content = JsonConvert.SerializeObject(result)
            };
        }
    }
}
